package structure;

/**
 * 单向链表
 */
public class LinkList {

    //头结点
    public Node head;

    //链表大小
    private int size;

    public LinkList() {
        this.head = new Node();
    }

    /**
     * 链尾添加
     * @param value
     */
    public void addData(Object value){
        Node newNode = new Node(value);

        Node temp = head;

        while (temp.next != null){
            temp = temp.next;
        }

        temp.next = newNode;
        size ++;
    }

    /**
     * 在指定位置插入
     * @param index
     * @param value
     */
    public void insertData(int index, Object value){
        if(index < 0 || index > size ){
            System.out.println("插入位置不合法");
            return;
        }

        int curPos = 0; //当前位置
        Node temp = head; //临时节点
        Node insertNode = new Node(value);//插入的新节点

        while (temp != null){

            if(curPos == index){
                insertNode.next = temp.next;
                temp.next = insertNode;

                size ++;
                return;
            }

            temp = temp.next;
            curPos ++;
        }
    }

    /**
     * 删除指定位置的节点
     * @param index
     */
    public void deleteData(int index){
        if(index < 0 || index > size ){
            System.out.println("插入位置不合法");
            return;
        }

        int curPos = 0; //当前位置
        Node temp = head; //临时节点

        while (temp != null){

            if(curPos == index){
                Node deleteNode = temp.next;
                temp.next = deleteNode.next;

                size --;
                return ;
            }

            temp = temp.next;
            curPos ++ ;
        }
    }

    /**
     * 遍历链表
     */
    public void traverse(){
        Node temp = head.next;

        System.out.println(" size = "+size);

        while (temp != null){

            System.out.println(" "+temp.data);

            temp = temp.next;
        }
    }

    /**
     * 获取链表大小
     * @return
     */
    public int getSize(){
        return  this.size;
    }

    /**
     * 就地反转链表
     */
    public void reverseList(){
        Node prev = head.next;
        Node pCur = prev.next;

        while(pCur != null){

            prev.next = pCur.next;
            pCur.next = head.next;
            head.next = pCur;
            pCur = prev.next;
        }

    }
}
